import {Component, OnInit} from '@angular/core';
import {PeerService, Block} from '../../service/peer.service';
import {NbToastrService} from '@nebular/theme';
import {NbToastStatus} from '@nebular/theme/components/toastr/model';
import {SERVER_IP} from '../../config';

@Component({
  selector: 'app-peer-search',
  templateUrl: './peer-search.component.html',
  styleUrls: ['./peer-search.component.css']
})


export class PeerSearchComponent implements OnInit {
  public peers: any = [];
  public peerData: any = [];
  public latestHashValue: string;
  private index: number = 0;


  constructor(private peerService: PeerService,
              private toastrService: NbToastrService,
  ) {
    this.loadData();
  }

  async loadData() {
    this.peers.push({ipAddress: SERVER_IP , port: '6001', isHost: true});
    this.peerData = await this.peerService.getPeers();
    if (this.peerData) {
      for (const p of this.peerData) {
        const peer = {ipAddress: p.split(':')[0], port: p.split(':')[1], isHost: false};
        this.peers.push(peer);
      }
      console.log(this.peers);
    }
  }

  onTestClick(event, peer) {
    this.peerService.getLatestHash(peer).subscribe(
      (data: Block) => {
      this.toastrService.show('节点正常', peer.ipAddress + ':' + peer.port, {status: NbToastStatus.SUCCESS});
    },
      (error) => {
        this.toastrService.show(error.name, '错误', {status: NbToastStatus.DANGER});
      }
    );
  }

  onGetClick(event, peer) {
    this.peerService.getLatestHash(peer).subscribe(
      (data: Block) => {
        this.toastrService.show('HASH值' + data.hash, peer.ipAddress + ':' + peer.port, {status: NbToastStatus.INFO});
      },
      (error) => {
        console.log(error);
        this.toastrService.show(error.name, '错误', {status: NbToastStatus.DANGER});
      });
  }

  getIsHost(peer) {
    return peer.isHost ? '主节点' : '非主节点';
  }
  ngOnInit() {
  }

}
